package com.carbonspark.gateway.auth;

import cn.dev33.satoken.stp.StpInterface;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.carbonspark.gateway.entity.AuthPermission;
import com.carbonspark.gateway.entity.AuthRole;
import com.carbonspark.gateway.redis.RedisUtil;
import com.google.gson.Gson;

import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义权限验证接口扩展
 *
 * @author: ChickenWing
 * @date: 2023/10/28
 */
@Component
public class StpInterfaceImpl implements StpInterface {

    @Resource
    private RedisUtil redisUtil;

    private static final String AUTH_PERMISSION_PREFIX = "auth.permission";
    private static final String AUTH_ROLE_PREFIX = "auth.role";

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        return getAuthFromRedis(loginId.toString(), AUTH_PERMISSION_PREFIX);
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        return getAuthFromRedis(loginId.toString(), AUTH_ROLE_PREFIX);
    }

    /**
     * 从 Redis 获取权限或角色列表
     */
    private List<String> getAuthFromRedis(String userId, String prefix) {
        String key = redisUtil.buildKey(prefix, userId);
        String value = redisUtil.get(key);
        if (StringUtils.isBlank(value)) {
            return Collections.emptyList();
        }
        try {
            return new Gson().fromJson(value, new TypeToken<List<String>>() {}.getType());
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
            return Collections.emptyList();
        }
    }
}